<template>
  <el-row style="height: 90%" :gutter="10">
    <el-col :span="10">
      <el-form
        :model="form"
        label-width="60px"
        :inline="true"
        label-position="left"
        v-if="showContent == 'jbxx'"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="次数">
              <el-input v-model="form.cs" style="width: 80px" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="笔录格式" label-width="80px">
              <el-select v-model="form.blgs" placeholder="" style="width: 100px">
                <el-option
                  v-for="item in blgsDic"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="人员类型" label-width="80px">
              <el-select v-model="form.rylx" placeholder="" style="width: 100px">
                <el-option
                  v-for="item in rylxDic"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="案件类型" label-width="80px">
          <el-select v-model="form.ajlx" placeholder="" style="width: 100px">
            <el-option
              v-for="item in ajlxDic"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="人员特征" label-width="80px">
          <el-select v-model="form.rytz" placeholder="" style="width: 150px">
            <el-option
              v-for="item in rytzDic"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="案件编号或名称" label-width="120px">
          <el-input v-model="form.ajbh" style="width: 150px" />
        </el-form-item>

        <el-form-item label="到案方式" label-width="80px">
          <el-select v-model="form.dafs" placeholder="" style="width: 150px">
            <el-option
              v-for="item in dafsDic"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="问话时间" label-width="120px">
          <el-date-picker
            v-model="whsj"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD hh:mm:ss"
          />
        </el-form-item>

        <el-form-item label="地点">
          <el-input v-model="form.dd" style="width: 400px" />
        </el-form-item>

        <el-form-item label="" label-width="80px">
          <el-select v-model="form.zjlx" placeholder="" style="width: 150px">
            <el-option
              v-for="item in zjlxDic"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-form-item label="号码">
            <el-input v-model="form.zjhm" style="width: 300px" @blur="zjhmChange" />
          </el-form-item>
        </el-form-item>

        <el-form-item label="被询问人" label-width="100px">
          <el-input v-model="form.bxwr" style="width: 150px" />
        </el-form-item>
        <el-form-item label="曾用名">
          <el-input v-model="form.cym" style="width: 150px" />
        </el-form-item>

        <el-form-item>
          <el-form-item label="性别" label-width="50px">
            <el-select v-model="form.xb" placeholder="" style="width: 70px">
              <el-option
                v-for="item in xbDic"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="出生日期" label-width="70px">
            <el-date-picker
              v-model="form.crrq"
              type="date"
              style="width: 120px"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item label="文化程度" label-width="70px" style="margin-right: 0">
            <el-select v-model="form.whcd" placeholder="" style="width: 100px">
              <el-option
                v-for="item in whcdDic"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form-item>

        <el-form-item>
          <el-form-item label="年龄">
            <el-input v-model="form.nl" style="width: 50px" />
          </el-form-item>

          <el-form-item label="国籍">
            <el-select v-model="form.gj" placeholder="" style="width: 80px">
              <el-option
                v-for="item in gjDic"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="民族">
            <el-select v-model="form.mz" placeholder="" style="width: 100px">
              <el-option
                v-for="item in mzDic"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-button @click="editJtcy()" type="primary">家</el-button>
        </el-form-item>

        <el-form-item>
          <el-form-item label="政治面貌" label-width="80px">
            <el-select v-model="form.zzmm" placeholder="" style="width: 150px">
              <el-option
                v-for="item in zzmmDic"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="联系电话" label-width="80px">
            <el-input v-model="form.lxdh" style="width: 150px" />
          </el-form-item>
        </el-form-item>

        <el-form-item label="户籍地址" label-width="80px">
          <el-input v-model="form.hjzz" style="width: 400px" />
        </el-form-item>

        <el-form-item label="现住址" label-width="80px">
          <el-input v-model="form.xzz" style="width: 400px" />
        </el-form-item>

        <el-form-item label="工作单位" label-width="80px">
          <el-input v-model="form.gzdw" style="width: 400px" />
        </el-form-item>

        <el-form-item label="">
          <el-checkbox
            v-model="form.sfgz"
            label="公职"
            size="large"
            true-value="是"
            false-value="否"
          />
        </el-form-item>

        <el-form-item label="记录人" label-width="80px">
          <el-input v-model="form.jlr" style="width: 150px" />
        </el-form-item>
        <el-form-item label="工作单位" label-width="100px">
          <el-input v-model="form.jlrgzdw" style="width: 150px" />
        </el-form-item>

        <el-form-item label="询问人" label-width="80px">
          <el-input v-model="form.xwr" style="width: 150px" />
        </el-form-item>
        <el-form-item label="工作单位" label-width="100px">
          <el-input v-model="form.xwrgzdw" style="width: 150px" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="switchBtn">{{ getBtnText() }}</el-button>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
      <div v-else-if="showContent == 'jxwh'" style="height: 100%">
        <el-button type="primary" @click="importAjtwmb">导入案件提问模板</el-button>
        <el-button type="primary" @click="openGzs">告知书</el-button>
        <el-table
          :data="ajtwmbData"
          border
          style="width: 100%; height: 85%"
          :empty-text="'暂无数据'"
          class="ajtwmbTable"
          :highlight-current-row="true"
          @cell-dblclick="handlerDblclick"
        >
          <el-table-column prop="twnr" label="双击以下提问内容，系统将自动将提问加入内容记录中" />
        </el-table>
        <el-row style="margin-top: 10px">
          <el-col :span="20"
            ><el-select v-model="answer1" placeholder="">
              <el-option
                v-for="item in answerTemplate1"
                :key="item"
                :label="item"
                :value="item"
              /> </el-select
          ></el-col>
          <el-col :span="4"
            ><el-button type="primary" @click="addAnswer1">加入回答</el-button></el-col
          >
        </el-row>
        <el-row style="margin-top: 10px">
          <el-col :span="20"
            ><el-select v-model="answer2" placeholder="">
              <el-option
                v-for="item in answerTemplate2"
                :key="item"
                :label="item"
                :value="item"
              /> </el-select
          ></el-col>
          <el-col :span="4"
            ><el-button type="primary" @click="addAnswer2">加入回答</el-button></el-col
          >
        </el-row>
        <el-row style="margin-top: 10px">
          <el-col>
            <el-button type="primary" @click="switchBtn">{{ getBtnText() }}</el-button>
            <el-button type="primary" @click="save">保存</el-button>
            <el-button @click="cancel">取消</el-button>
          </el-col>
        </el-row>
      </div>
    </el-col>
    <el-col :span="14"
      ><QuillEditor
        theme="snow"
        v-model:content="form.blnr"
        content-type="html"
        ref="myQuillEditor"
        @ready="onEditorReady"
        @text-change="onTextChange"
    /></el-col>
  </el-row>

  <!-- <el-row>
    <el-col style="margin-top: 80px; text-align: center" :span="12">
      <el-button type="primary" @click="switchBtn">{{ getBtnText() }}</el-button>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-col>
  </el-row> -->

  <el-dialog
    v-model="showJtcyEdit"
    title="家庭成员"
    width="50%"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :before-close="closeJtcyEdit"
  >
    <JtcyEdit :blid="form.id" ref="jtcyEditRef"></JtcyEdit>
  </el-dialog>

  <div :style="tipStyle" class="tip" @dblclick="tipDbclick" ref="tipRef">
    我叫{{ form.bxwr }}，曾用名{{ form.cym }}，男，{{ form.crrq }}出生，{{ form.mz }}，{{
      form.whcd
    }}文化程度，户籍所在地{{ form.hjzz }}，现在{{ form.gzdw }}工作，{{ form.zjlx }}号码{{
      form.zjhm
    }}，联系电话{{ form.lxdh }}。
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted,onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  blgsDic,
  rylxDic,
  ajlxDic,
  rytzDic,
  dafsDic,
  zjlxDic,
  xbDic,
  whcdDic,
  gjDic,
  zzmmDic,
  mzDic
} from '../../config/dic'
import moment from 'moment'
import JtcyEdit from './jtcyEdit.vue'
import { answerTemplate1, answerTemplate2 } from '../../config/answer'
const router = useRouter()
const form = reactive({
  id: '',
  cs: '',
  blgs: '',
  rylx: '',
  ajlx: '',
  rytz: '',
  ajbh: '',
  dafs: '',
  kssj: '',
  jssj: '',
  dd: '',
  zjlx: '',
  zjhm: '',
  bxwr: '',
  cym: '',
  xb: '',
  crrq: '',
  whcd: '',
  nl: '',
  gj: '',
  mz: '',
  zzmm: '',
  lxdh: '',
  hjzz: '',
  xzz: '',
  gzdw: '',
  sfgz: '',
  blnr: '',
  jlr: '',
  jlrgzdw: '',
  xwr: '',
  xwrgzdw: ''
})

const whsj = ref([moment(new Date()).format('YYYY-MM-DD HH:mm:ss')])

const showJtcyEdit = ref(false)
const jtcyEditRef = ref()

const showContent = ref('jbxx')

const ajtwmbData = ref([])

const answer1 = ref('')
const answer2 = ref('')
const myQuillEditor = ref()

const tipStyle = ref({})

const tipRef = ref()

onMounted(async () => {
  const str = router.currentRoute.value.query.data
  if (str) {
    const data = JSON.parse(str)
    Object.assign(form, data)
  }

  if (form.kssj) {
    whsj.value[0] = form.kssj
  }

  if (form.jssj) {
    whsj.value[1] = form.jssj
  }

  document.addEventListener('click', handleClickOutside)
})

// 在组件卸载时，移除文档的点击事件监听器
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

function getBtnText() {
  if (showContent.value == 'jbxx') {
    return '继续问话'
  } else if (showContent.value == 'jxwh') {
    return '基本信息'
  }
}

function switchBtn() {
  if (showContent.value == 'jbxx') {
    showContent.value = 'jxwh'
  } else if (showContent.value == 'jxwh') {
    showContent.value = 'jbxx'
  }
}

async function save() {
  const tableName = 'bl_xw'

  form.kssj = whsj.value[0]

  if (whsj.value[1]) {
    form.jssj = whsj.value[1]
  } else {
    form.jssj = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
  }

  let res
  if (form.id) {
    res = await window.db.update(
      `UPDATE ${tableName} SET cs=?, blgs=?, rylx=?, ajlx=?, rytz=?, ajbh=?, dafs=?, kssj=?, jssj=?, dd=?, zjlx=?, zjhm=?, bxwr=?, cym=?, xb=?, crrq=?, whcd=?, nl=?, gj=?, mz=?, zzmm=?, lxdh=?, hjzz=?, xzz=?, gzdw=?, sfgz=?, blnr=?,jlr=?,jlrgzdw=?,xwr=?,xwrgzdw=? WHERE id=?;`,
      form.cs,
      form.blgs,
      form.rylx,
      form.ajlx,
      form.rytz,
      form.ajbh,
      form.dafs,
      form.kssj,
      form.jssj,
      form.dd,
      form.zjlx,
      form.zjhm,
      form.bxwr,
      form.cym,
      form.xb,
      form.crrq,
      form.whcd,
      form.nl,
      form.gj,
      form.mz,
      form.zzmm,
      form.lxdh,
      form.hjzz,
      form.xzz,
      form.gzdw,
      form.sfgz,
      form.blnr,
      form.jlr,
      form.jlrgzdw,
      form.xwr,
      form.xwrgzdw,
      form.id
    )
  } else {
    res = await window.db.update(
      `INSERT INTO ${tableName} (cs, blgs, rylx, ajlx, rytz, ajbh, dafs, kssj, jssj, dd, zjlx, zjhm, bxwr, cym, xb, crrq, whcd, nl, gj, mz, zzmm, lxdh, hjzz, xzz, gzdw, sfgz, blnr) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`,
      form.cs,
      form.blgs,
      form.rylx,
      form.ajlx,
      form.rytz,
      form.ajbh,
      form.dafs,
      form.kssj,
      form.jssj,
      form.dd,
      form.zjlx,
      form.zjhm,
      form.bxwr,
      form.cym,
      form.xb,
      form.crrq,
      form.whcd,
      form.nl,
      form.gj,
      form.mz,
      form.zzmm,
      form.lxdh,
      form.hjzz,
      form.xzz,
      form.gzdw,
      form.sfgz,
      form.blnr
    )
    form.id = res.lastInsertRowid
  }

  if (res.changes > 0) {
    ElMessage.success('保存成功！')
    return true
  } else {
    ElMessage.error('保存失败！')
    return false
  }
}

async function cancel() {
  router.go(-1)
}

async function editJtcy() {
  if (!form.id) {
    ElMessageBox.confirm('添加家庭成员需要先保存基本信息，是否确定保存?', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      if (await save()) {
        showJtcyEdit.value = true
      }
    })
  } else {
    showJtcyEdit.value = true
  }
}

const closeJtcyEdit = (done: () => void) => {
  ElMessageBox.confirm('关闭前是否保存?')
    .then(() => {
      jtcyEditRef.value.save()
      done()
    })
    .catch(() => {
      // catch error
      done()
    })
}

const importAjtwmb = async () => {
  let path = await window.operation.openFADir()
  if (!path) {
    return
  }
  let data = await window.operation.readFileContent(path)
  console.log(data)
  const lines = data.split(/\r?\n/)
  lines.forEach((line, index) => {
    ajtwmbData.value.push({
      twnr: line
    })
  })
}

const handlerDblclick = (row, column, cell, event) => {
  if (form.blnr.length > 0 && !form.blnr.endsWith('\n')) {
    insertTextAtCursor('\n')
  }
  insertTextAtCursor(`问：${row.twnr}\n答：`)

  if (row.twnr.indexOf('你的个人情况？') > -1) {
    getCursorPagePosition()
  }
}

const addAnswer1 = () => {
  insertTextAtCursor(answer1.value)
}
const addAnswer2 = () => {
  insertTextAtCursor(answer2.value)
}

function insertTextAtCursor(text) {
  const quill = myQuillEditor.value.getQuill() // 获取Quill实例
  quill.focus()
  const range = quill.getSelection() // 获取当前光标位置信息
  quill.insertText(range.index, text) // 在光标位置插入文本
}

function openGzs() {
  window.operation.openDirectoryInExplorer()
}

function zjhmChange() {
  if (form.zjhm.length == 18 && !form.crrq) {
    form.crrq = extractBirthDateFromIDCard(form.zjhm)
  }
}

function extractBirthDateFromIDCard(idCard) {
  // 检查身份证号是否为18位
  if (idCard.length !== 18) {
    throw new Error('身份证号必须是18位')
  }

  // 截取出生日期部分（第7位到第14位）
  const birthDatePart = idCard.substring(6, 14)

  // 拆分年月日并格式化为 yyyy-mm-dd
  const year = birthDatePart.substring(0, 4)
  const month = birthDatePart.substring(4, 6)
  const day = birthDatePart.substring(6, 8)

  // 返回格式化后的日期
  return `${year}-${month}-${day}`
}

function getCursorPagePosition() {
  const quillInstance = myQuillEditor.value.getQuill() // 获取 Quill 实例
  const selection = quillInstance.getSelection() // 获取光标位置

  if (selection && selection.index !== null) {
    const bounds = quillInstance.getBounds(selection.index) // 获取光标在编辑器中的边界信息
    if (bounds) {
      // 获取编辑器容器的 DOM 元素
      const editorContainer = quillInstance.container
      // 计算光标相对于页面的 X 和 Y 坐标
      const rect = editorContainer.getBoundingClientRect()
      let cursorX = bounds.left + rect.left + window.scrollX
      let cursorY = bounds.top + rect.top + window.scrollY
      console.log(`光标位置：X=${cursorX}, Y=${cursorY}`)
      tipStyle.value.left = cursorX + 'px'
      tipStyle.value.top = cursorY + 'px'
      tipStyle.value.display = 'block'
    } else {
    }
  } else {
  }
}

function onEditorReady(quill) {
  console.log('Quill 编辑器初始化完成', quill)
  // 在这里可以对 Quill 实例进行操作，例如设置默认格式或添加自定义模块
}

let isInitialized = false
function onTextChange(params) {
  // 检测内容变化的原因
  if (!isInitialized) {
    // 如果是通过 API 设置内容，并且尚未标记为初始化完成
    console.log('内容初始化完成')
    isInitialized = true // 标记为初始化完成
    const quill = myQuillEditor.value.getQuill() // 获取Quill实例
    const length = quill.getLength() // 获取当前内容的总长度
    quill.setSelection(length - 1, 0) // 将光标定位到文本最后
  }
}

function tipDbclick() {
  insertTextAtCursor(tipRef.value.textContent)
  tipStyle.value.display = 'none'
}

// 点击文档其他区域时隐藏弹出框
const handleClickOutside = (event) => {
  if (tipRef.value && !tipRef.value.contains(event.target)) {
    tipStyle.value.display = 'none'
  }
}
</script>

<style lang="scss" scoped>
.ajtwmbTable ::v-deep(.el-table__body-wrapper) {
  color: red;
}
.tip {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 500px;
  height: 50px;
  z-index: 9999;
  display: none;
  background-color: #fff;
  padding: 20px;
  border: 2px solid #ccc; /* 边框样式 */
  border-radius: 8px; /* 圆角 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 阴影效果 */
  cursor: pointer;
}
</style>
